package cn.xz.gobang.dialog

import android.view.Gravity
import android.widget.EditText
import android.widget.TextView
import cn.xz.gobang.R
import cn.xz.gobang.base.BaseDialogRxFragment
import cn.xz.gobang.bean.*
import cn.xz.gobang.net.OkHttpUtil
import cn.xz.gobang.util.GetDataUtils
import cn.xz.gobang.util.JsonUtil
import cn.xz.gobang.util.SessionUtils
import okhttp3.FormBody
import okhttp3.RequestBody

/**
 * 修改名字弹窗
 * */
class EditNameDialog: BaseDialogRxFragment() {

    private var tvTitle: TextView? = null
    private var tvCancel: TextView? = null
    private var tvOver: TextView? = null
    private var etInput: EditText? = null

    private var mName: String = ""

    private var mClickListener: OnClickListener? = null

    companion object {
        fun newInstance(
            mName: String,
            mClickListener: OnClickListener
        ): EditNameDialog {
            val editNameDialog = EditNameDialog()
            editNameDialog.mName = mName
            editNameDialog.mClickListener = mClickListener
            return editNameDialog
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.item_edit_name
    }

    override fun configDialog() {
        this.setDialogSize(gravity = Gravity.CENTER,width = 300)
    }

    override fun initViews() {

        dialog?.let {
            tvTitle = it.findViewById(R.id.tv_title)
            tvOver = it.findViewById(R.id.tv_over)
            tvCancel = it.findViewById(R.id.tv_cancel)
            etInput = it.findViewById(R.id.et_input)
        }

        //点击外部不隐藏
        dialog?.setCancelable(false)
        dialog?.setCanceledOnTouchOutside(false)

        tvTitle?.text = "当前昵称:${mName}"

        //点击事件
        initEvent()
    }


    private fun initEvent(){
        if (tvOver != null){
            tvOver?.setOnClickListener {
                putTxt()
                dismiss()
            }
        }
        if (tvCancel != null){
            tvCancel?.setOnClickListener {
                dismiss()
            }
        }
    }

    private fun putTxt(){
        if (etInput != null && etInput!!.text.toString().isNotEmpty()){
            //获取当前用户信息
            GetDataUtils.onUserData(CommonLib.getUserID,object :GetDataUtils.OnReadDataListener{
                override fun success(bean: UserData) {
                    bean.name = etInput!!.text.toString()
                    putContent(bean)
                }
                override fun error() {
                }
            })
        }
    }

    private fun putContent(d: UserData){
        //更新当前用户数据
        GetDataUtils.onWriteData(CommonLib.getUserID, JsonUtil.serializeAsString(d),object :GetDataUtils.OnWriteDataListener{
            override fun success() {
                mClickListener?.onYes()
            }
        })
    }


    interface OnClickListener {
        fun onYes()
    }

}